<template>
  <div class="bookmark-container">
    <div class="page-header">
      <div class="page-title">网络地址管理</div>
      <el-button type="primary" @click="handleAdd">添加网址</el-button>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="标题">
        <el-input v-model="searchForm.title" placeholder="请输入标题" clearable />
      </el-form-item>
      <el-form-item label="分类">
        <el-input v-model="searchForm.category" placeholder="请输入分类" clearable />
      </el-form-item>
      <el-form-item label="收藏">
        <el-select v-model="searchForm.favorite" placeholder="请选择" clearable>
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 分类标签 -->
    <div class="category-tags">
      <el-tag
        :effect="currentCategory === '' ? 'dark' : 'plain'"
        @click="filterByCategory('')"
      >
        全部
      </el-tag>
      <el-tag
        v-for="category in categoryList"
        :key="category"
        :effect="currentCategory === category ? 'dark' : 'plain'"
        @click="filterByCategory(category)"
      >
        {{ category }}
      </el-tag>
    </div>

    <!-- 书签列表 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="bookmark in bookmarkList" :key="bookmark.id" class="bookmark-item">
        <el-card shadow="hover">
          <div class="bookmark-header">
            <span class="bookmark-title" :title="bookmark.title">{{ bookmark.title }}</span>
            <el-button
              type="text"
              :class="['favorite-btn', { 'is-favorite': bookmark.favorite === 1 }]"
              @click.stop="toggleFavorite(bookmark)"
            >
              <i class="el-icon-star-on"></i>
            </el-button>
          </div>
          <div class="bookmark-url" :title="bookmark.url">
            <a :href="bookmark.url" target="_blank">{{ bookmark.url }}</a>
          </div>
          <div class="bookmark-category" v-if="bookmark.category">
            <el-tag size="mini">{{ bookmark.category }}</el-tag>
          </div>
          <div class="bookmark-description" v-if="bookmark.description">
            {{ bookmark.description }}
          </div>
          <div class="bookmark-actions">
            <el-button type="text" size="mini" @click.stop="handleEdit(bookmark)">编辑</el-button>
            <el-button type="text" size="mini" @click.stop="handleDelete(bookmark)">删除</el-button>
            <el-button type="text" size="mini" @click.stop="copyUrl(bookmark.url)">复制链接</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 空状态 -->
    <el-empty v-if="bookmarkList.length === 0 && !loading" description="暂无网址"></el-empty>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-spinner></el-spinner>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page.sync="pagination.pageNum"
        :page-sizes="[12, 24, 36, 48]"
        :page-size.sync="pagination.pageSize"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @closed="resetForm">
      <el-form ref="bookmarkForm" :model="bookmarkForm" :rules="bookmarkRules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="bookmarkForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="网址" prop="url">
          <el-input v-model="bookmarkForm.url" placeholder="请输入网址" />
        </el-form-item>
        <el-form-item label="分类">
          <el-input v-model="bookmarkForm.category" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="bookmarkForm.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="收藏">
          <el-switch v-model="bookmarkForm.favorite" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="bookmarkForm.sort" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBookmarkList, addBookmark, updateBookmark, deleteBookmark, getBookmarkDetail, toggleFavorite, updateSort } from '@/api/bookmark'

export default {
  name: 'Bookmark',
  data() {
    return {
      // 搜索表单
      searchForm: {
        title: '',
        category: '',
        favorite: ''
      },
      // 分页
      pagination: {
        pageNum: 1,
        pageSize: 12,
        total: 0
      },
      // 书签列表
      bookmarkList: [],
      // 分类列表
      categoryList: [],
      currentCategory: '',
      // 加载状态
      loading: false,
      // 对话框
      dialogVisible: false,
      dialogTitle: '添加网址',
      submitLoading: false,
      // 表单
      bookmarkForm: {
        id: null,
        title: '',
        url: '',
        category: '',
        description: '',
        favorite: 0,
        sort: 0
      },
      // 表单校验规则
      bookmarkRules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        url: [
          { required: true, message: '请输入网址', trigger: 'blur' },
          { pattern: /^https?:\/\/.+/, message: '请输入有效的网址', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取书签列表
    fetchData() {
      this.loading = true
      getBookmarkList({
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        title: this.searchForm.title,
        category: this.searchForm.category,
        favorite: this.searchForm.favorite
      })
        .then(response => {
          const { data } = response
          this.bookmarkList = data.records
          this.pagination.total = data.total
          this.loading = false
          
          // 提取分类列表
          this.extractCategories()
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 提取分类列表
    extractCategories() {
      const categories = new Set()
      this.bookmarkList.forEach(bookmark => {
        if (bookmark.category) {
          categories.add(bookmark.category)
        }
      })
      this.categoryList = Array.from(categories)
    },
    // 按分类筛选
    filterByCategory(category) {
      this.currentCategory = category
      this.searchForm.category = category
      this.pagination.pageNum = 1
      this.fetchData()
    },
    // 搜索
    handleSearch() {
      this.pagination.pageNum = 1
      this.fetchData()
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        title: '',
        category: '',
        favorite: ''
      }
      this.currentCategory = ''
      this.handleSearch()
    },
    // 分页大小变化
    handleSizeChange() {
      this.fetchData()
    },
    // 页码变化
    handleCurrentChange() {
      this.fetchData()
    },
    // 添加书签
    handleAdd() {
      this.dialogTitle = '添加网址'
      this.bookmarkForm = {
        id: null,
        title: '',
        url: '',
        category: '',
        description: '',
        favorite: 0,
        sort: 0
      }
      this.dialogVisible = true
    },
    // 编辑书签
    handleEdit(row) {
      this.dialogTitle = '编辑网址'
      getBookmarkDetail(row.id)
        .then(response => {
          this.bookmarkForm = { ...response.data }
          this.dialogVisible = true
        })
    },
    // 删除书签
    handleDelete(row) {
      this.$confirm('确认删除该网址吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteBookmark(row.id)
            .then(() => {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.fetchData()
            })
        })
        .catch(() => {})
    },
    // 切换收藏状态
    toggleFavorite(row) {
      toggleFavorite(row.id)
        .then(() => {
          row.favorite = row.favorite === 1 ? 0 : 1
          this.$message({
            type: 'success',
            message: row.favorite === 1 ? '已添加到收藏' : '已取消收藏'
          })
        })
    },
    // 复制链接
    copyUrl(url) {
      const textarea = document.createElement('textarea')
      textarea.value = url
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      this.$message({
        message: '链接已复制到剪贴板',
        type: 'success'
      })
    },
    // 提交表单
    submitForm() {
      this.$refs.bookmarkForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          if (this.bookmarkForm.id) {
            // 更新
            updateBookmark(this.bookmarkForm)
              .then(() => {
                this.$message({
                  type: 'success',
                  message: '更新成功'
                })
                this.dialogVisible = false
                this.fetchData()
                this.submitLoading = false
              })
              .catch(() => {
                this.submitLoading = false
              })
          } else {
            // 添加
            addBookmark(this.bookmarkForm)
              .then(() => {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.dialogVisible = false
                this.fetchData()
                this.submitLoading = false
              })
              .catch(() => {
                this.submitLoading = false
              })
          }
        }
      })
    },
    // 重置表单
    resetForm() {
      if (this.$refs.bookmarkForm) {
        this.$refs.bookmarkForm.resetFields()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.bookmark-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .category-tags {
    margin-bottom: 20px;
    
    .el-tag {
      margin-right: 10px;
      margin-bottom: 10px;
      cursor: pointer;
    }
  }
  
  .bookmark-item {
    margin-bottom: 20px;
    
    .el-card {
      height: 180px;
      position: relative;
    }
    
    .bookmark-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      
      .bookmark-title {
        font-size: 16px;
        font-weight: bold;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        flex: 1;
      }
      
      .favorite-btn {
        font-size: 18px;
        color: #dcdfe6;
        
        &.is-favorite {
          color: #f7ba2a;
        }
      }
    }
    
    .bookmark-url {
      margin-bottom: 10px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      
      a {
        color: #409eff;
        text-decoration: none;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
    
    .bookmark-category {
      margin-bottom: 10px;
    }
    
    .bookmark-description {
      font-size: 14px;
      color: #606266;
      height: 40px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
    
    .bookmark-actions {
      position: absolute;
      bottom: 10px;
      right: 20px;
    }
  }
  
  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: center;
  }
}
</style> 